﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client;
using System.Configuration;
using System.Data;

namespace Testify
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        int requiredPermission;
        int userPermission;

        protected void Page_Init(object sender, EventArgs e)
        {
            this.lblPageTitle.Text = Page.Title;
            if (this.Page.Title != "Log In")
            {
                setRequiredPremission();
                setPageContent();
            }

            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated && Page.Title != "Log In")
            {
                Response.Redirect("~/Account/Login.aspx");
            }
            else
            {
               loadNavigationMenu();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void HeadLoginStatus_LoggedOut(object sender, EventArgs e)
        {
            Session.Clear();
        }

        protected void setRequiredPremission()
        {
            string queryString1 = @"SELECT PERMISSION_LEVEL
                                      FROM SINGULARITY.SECURITY
                                     WHERE PAGE_NAME = :PAGE_NAME
                                        OR :PAGE_NAME is NULL
                                       AND PAGE_NAME  is NULL";

            OracleConnection myConnection1 = new OracleConnection(ConfigurationManager.ConnectionStrings["Singularity"].ConnectionString);
            OracleCommand cmdGetPermission = new OracleCommand(queryString1, myConnection1);
            cmdGetPermission.BindByName = true;
            OracleDataReader myReader1 = default(OracleDataReader);
            OracleCommand cmdCreatePremissions = new OracleCommand("SECURITIES.createPagePermissions", myConnection1);
            cmdCreatePremissions.CommandType = CommandType.StoredProcedure;
            cmdCreatePremissions.BindByName = true;

            try
            {
                myConnection1.Open();

                cmdGetPermission.Parameters.Clear();
                cmdGetPermission.Parameters.Add("PAGE_NAME", this.Page.Title.Trim());
                myReader1 = cmdGetPermission.ExecuteReader();
                if (myReader1.HasRows)
                {
                    // set requried premissions
                    myReader1.Read();
                    requiredPermission = int.Parse(myReader1["PERMISSION_LEVEL"].ToString());
                    myReader1.Close();
                }
                else
                {
                    // insert default premission into database
                    try
                    {
                        cmdCreatePremissions.Parameters.Clear();
                        cmdCreatePremissions.Parameters.Add("p_PageName", this.Page.Title);
                        cmdCreatePremissions.Parameters.Add("p_PermissionLevel", 10);

                        cmdCreatePremissions.ExecuteNonQuery();
                        requiredPermission = 10;
                    }
                    catch (Exception ex)
                    {
                        this.lblPermissionsError.Text += "Error creating the permissions.<br />";
                        this.lblPermissionsError.Text += ex.Message + "<br />";
                    }
                }
            }
            catch (Exception ex)
            {
                Utilities.logError(Page.Title, ex);
                try
                {
                    myReader1.Close();
                }
                catch
                {
                }
            }
            finally
            {
                myConnection1.Close();
            }
        }

        protected void setPageContent()
        {
            if (Session["UserID"] == null)
            {
               this.lblAccessDenied.Text = "Please login to view this page<br />";
               this.hypLogin.Enabled = true;
               this.MainContent.Visible = false;
               this.pnlAccessDenied.Visible = true;
            }
            else
            {
                userPermission = Utilities.getUserPermission(Session["UserID"].ToString());
                Session["UserPermission"] = userPermission;
                if (userPermission >= requiredPermission)
                {
                    this.MainContent.Visible = true;
                    this.pnlAccessDenied.Visible = false;
                }
                else
                {
                    this.MainContent.Visible = false;
                    this.pnlAccessDenied.Visible = true;
                }
            }
        }

        protected void loadNavigationMenu()
        {

           if (userPermission >= Utilities.getUserTypePermission("Administration") || userPermission >= Utilities.getUserTypePermission("Sys_Admin"))
           {
              // Admin Links
              MenuItemCollection adminMenu = new MenuItemCollection();
              adminMenu.Clear();
              adminMenu.Add(new MenuItem("Actions", null, null, "~/Courses/AdminActions.aspx"));
              adminMenu.Add(new MenuItem("Enrollment", null, null, "~/Courses/Enrollment.aspx"));
              adminMenu.Add(new MenuItem("Users", null, null, "~/Account/Users.aspx"));
              adminMenu.Add(new MenuItem("Security", null, null, "~/Tools/Security.aspx"));
              adminMenu.Add(new MenuItem("Support", null, null, "~/Support.aspx"));

              foreach (MenuItem r in adminMenu)
              {
                 this.NavigationMenu.Items.Add(new MenuItem(r.Text, null, null, r.NavigateUrl));
                 this.smallMenuActual.Items.Add(new MenuItem(r.Text, null, null, r.NavigateUrl));
              }

              // Sys_Admin link
              if (userPermission >= Utilities.getUserTypePermission("Sys_Admin"))
              {
                 
                 MenuItemCollection sysAdminMenu = new MenuItemCollection();
                 sysAdminMenu.Clear();
                 sysAdminMenu.Add(new MenuItem("Error Log", null, null, "~/Tools/ErrorLog.aspx"));

                 foreach (MenuItem r in sysAdminMenu)
                 {
                    this.NavigationMenu.Items.Add(new MenuItem(r.Text, null, null, r.NavigateUrl));
                    this.smallMenuActual.Items.Add(new MenuItem(r.Text, null, null, r.NavigateUrl));
                 }
              }

           }
           else if (userPermission >= Utilities.getUserTypePermission("Teacher"))
           {
              // Teacher Links
              MenuItemCollection teacherMenu = new MenuItemCollection();
              teacherMenu.Clear();
              teacherMenu.Add(new MenuItem("Classes", null, null, "~/Courses/Classes.aspx"));
              teacherMenu.Add(new MenuItem("Create Tests", null, null, "~/Tests/CreateTests.aspx"));
              teacherMenu.Add(new MenuItem("Assign Tests", null, null, "~/Tests/AssignTest.aspx"));
              teacherMenu.Add(new MenuItem("Statistics", null, null, "~/Grades/GradeStatistics.aspx"));
              teacherMenu.Add(new MenuItem("Grading", null, null, "~/Grades/ManualGrading.aspx"));

              foreach (MenuItem r in teacherMenu)
              {
                 this.NavigationMenu.Items.Add(new MenuItem(r.Text, null, null, r.NavigateUrl));
                 this.smallMenuActual.Items.Add(new MenuItem(r.Text, null, null, r.NavigateUrl));
              }
           }
           else if (userPermission >= Utilities.getUserTypePermission("Student"))
           {
              // Student Links
              MenuItemCollection teacherMenu = new MenuItemCollection();
              teacherMenu.Clear();
              teacherMenu.Add(new MenuItem("Desk", null, null, "~/Default.aspx"));
              teacherMenu.Add(new MenuItem("View Grades", null, null, "~/Grades/ViewGrades.aspx"));

              foreach (MenuItem r in teacherMenu)
              {
                 this.NavigationMenu.Items.Add(new MenuItem(r.Text, null, null, r.NavigateUrl));
                 this.smallMenuActual.Items.Add(new MenuItem(r.Text, null, null, r.NavigateUrl));
              }
           }
           else
           {
              this.NavigationMenu.Items.Add(new MenuItem("", null, null, ""));
           }
        }
    }
}
